package cn.wolfcode.web.controller;


import cn.wolfcode.common.constants.CommonConstants;
import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.CommonCodeMsg;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.redis.CommonRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.vo.PayResult;
import cn.wolfcode.vo.PayVo;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/orderPay")
@RefreshScope
public class OrderPayController {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequireLogin
    @PostMapping("/integral")
    public Result<?> integralPay(String orderNo, @RequestHeader(CommonConstants.TOKEN_NAME) String token) {
        UserInfo userInfo = getUserByToken(token);
        orderInfoService.integralPay(orderNo, userInfo.getPhone());
        return Result.success("支付成功");
    }

    @RequireLogin
    @GetMapping("/refund")
    public Result<?> refund(String orderNo, @RequestHeader(CommonConstants.TOKEN_NAME) String token) {
        UserInfo userInfo = getUserByToken(token);
        orderInfoService.doRefund(orderNo, userInfo.getPhone());
        return Result.success("退款成功");
    }

    @PostMapping("/paySuccess")
    public Result<?> paySuccess(@RequestBody PayResult result) {
        orderInfoService.paySuccess(result);
        return Result.success("处理成功");
    }

    @GetMapping("/findPayVoByOrderNo")
    public Result<PayVo> findPayVoByOrderNo(String orderNo, @RequestHeader(CommonConstants.TOKEN_NAME) String token) {
        OrderInfo orderInfo = orderInfoService.findById(orderNo);
        UserInfo user = getUserByToken(token);
        if (user == null || !orderInfo.getUserId().equals(user.getPhone())) {
            throw new BusinessException(CommonCodeMsg.ILLEGAL_OPERATION);
        }

        PayVo vo = new PayVo();
        vo.setOutTradeNo(orderNo);
        vo.setSubject(orderInfo.getProductName());
        vo.setTotalAmount(orderInfo.getSeckillPrice().toString());
        vo.setBody("叩丁狼秒杀");

        return Result.success(vo);
    }

    private UserInfo getUserByToken(String token) {
        return JSON.parseObject(redisTemplate.opsForValue().get(CommonRedisKey.USER_TOKEN.getRealKey(token)), UserInfo.class);
    }
}
